/**
 * switch.js
 * @author Ulyan Sobin
 * @description Switch module
 */

const http = require("http");
const { ErrorView } = require(".");
const { WebNode, WebClient } = require("./cube-web");

class Switch extends WebNode {

	/** 
	 * @private
	 * @type { Object.<string, WebNode> }
	 */
	switchTree;

	/**
	 * @private
	 * @type { WebNode }
	 */
	default;

	/**
	 * `tree` is an object which map hostname to webnode
	 * @param { Object.<string, WebNode> } tree
	 */
	constructor (tree) {
		super();
		this.switchTree = tree;
		if (tree.default instanceof WebNode)
			this.default = tree.default;
		else
			this.default = new ErrorView(404, "NOT FOUND");
	}

	/**
	 * 
	 * @param {WebClient} client 
	 */
	route(client) {
		if (client.request.origin instanceof http.IncomingMessage) {
			/** @type { http.IncomingMessage } */
			let req = client.request.origin;
			let host = req.headers.host;
			if (typeof(host) != "string") host = "";
			host = host.split(':')[0];
			let node = this.switchTree[host];
			if (node instanceof WebNode)
				node.route(client);
			else
				this.default.route(client);
		}
	}
}

module.exports.Switch = Switch;